package com.net.model.base.activity;

import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.drug.lib.util.DLog;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.load.LoadStatus;
import com.net.model.base.Resource;
import com.net.model.utils.Constant;
import com.net.model.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by leo
 * on 2019/10/15.
 */
public abstract class BaseLoadVMActivity<VB extends ViewBinding, VM extends BaseViewModel> extends BaseLoadVBActivity<VB> {
    protected VM mViewModel;

    @Override
    protected void initialize() {
        createViewModel();
        dataChange();
        loadPage.getBuilder().setRetryButtonClick(() -> requestNetwork());
    }

    public void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
        }
    }

    @Override
    protected boolean immersive() {
        return true;
    }

    //所有监听放这里
    protected abstract void dataChange();

    protected abstract void requestNetwork();


    public abstract class OnCallback<T> implements Resource.OnHandleCallback<T> {
        boolean isLoading = false;

        public OnCallback(boolean isLoading) {
            this.isLoading = isLoading;
        }

        public OnCallback() {
        }

        @Override
        public void onLoading() {
            if (isLoading) loadPage.getBuilder().show(LoadStatus.LOADING);
            DLog.d("加载中.....");
        }


        @Override
        public void onFailure(Integer code, String message) {
            if (loadPage.isViEnable()) {
                if (code == Constant.EMPTY_DATA_ERROR) {
                    getHandler().postDelayed(() -> loadPage.getBuilder().dismiss(), 2000);
                } else {
                    getHandler().postDelayed(() -> loadPage.getBuilder().setMessage(message).show(LoadStatus.LOAD_FAILD), 2000);
                }
                return;
            }
            if (code != Constant.EMPTY_DATA_ERROR) {
                ToastUtil.show(message);
            }
        }

        @Override
        public void onCompleted() {
            DLog.d("加载完成");
            if (isLoading) {
                getHandler().postDelayed(() -> loadPage.getBuilder().show(LoadStatus.SUCCESS), 2000);
            }
        }

        @Override
        public void onProgress(int precent, long total) {

        }
    }


}
